package com.dawn.module.hospital.util;


import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.Period;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.regex.Pattern;

/**
 * @description:
 * @author: cnsu-cmh
 * @time: 2024/8/7 22:49
 */
public class DateUtils {
    private static Calendar calS=Calendar.getInstance();
    private static Pattern p   =   Pattern.compile("\\d{4}-\\d{2}-\\d{2}");

    private static String[] parsePatterns = {"yyyy-MM-dd",
            "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm", "yyyy-MM", "yyyy/MM/dd",
            "yyyy/MM/dd HH:mm:ss", "yyyy/MM/dd HH:mm", "yyyy/MM", "yyyy.MM.dd",
            "yyyy.MM.dd HH:mm:ss", "yyyy.MM.dd HH:mm", "yyyy.MM","yyyyMMdd","yyyyMMddHHmmss"};

    public static String FORMAT_YMD = "yyyy-MM-dd";
    public static String FORMAT_DEFAULT = "yyyy-MM-dd HH:mm:ss";

    /**
     * 得到当前日期字符串 格式（yyyy-MM-dd）
     */
    public static String getDate() {
        return getDate("yyyy-MM-dd");
    }

    /**
     * 得到当前日期字符串 格式（yyyy-MM-dd） pattern可以为："yyyy-MM-dd" "HH:mm:ss" "E"
     */
    public static String getDate(String pattern) {
        return DateFormatUtils.format(new Date(), pattern);
    }

    /**
     * 得到日期字符串 默认格式（yyyy-MM-dd） pattern可以为："yyyy-MM-dd" "HH:mm:ss" "E"
     */
    public static String formatDate(Date date, Object... pattern) {
        String formatDate = null;
        if (pattern != null && pattern.length > 0) {
            formatDate = DateFormatUtils.format(date, pattern[0].toString());
        } else {
            formatDate = DateFormatUtils.format(date, "yyyy-MM-dd");
        }
        return formatDate;
    }

    /**
     * 得到日期时间字符串，转换格式（yyyy-MM-dd HH:mm:ss）
     */
    public static String formatDateTime(Date date) {
        return formatDate(date, "yyyy-MM-dd HH:mm:ss");
    }

    /**
     * 得到当前时间字符串 格式（HH:mm:ss）
     */
    public static String getTime() {
        return formatDate(new Date(), "HH:mm:ss");
    }

    /**
     * 得到当前日期和时间字符串 格式（yyyy-MM-dd HH:mm:ss）
     */
    public static String getDateTime() {
        return formatDate(new Date(), "yyyy-MM-dd HH:mm:ss");
    }

    public static String getDateHHMMSS() {
        return formatDate(new Date(), "HHmmss");
    }

    /**
     * 得到当前日期和时间字符串 格式（yyyy-MM-dd HH:mm:ss）
     */
    public static String getTimeYYMMDD() {
        return formatDate(new Date(), "yyyy-MM-dd");
    }

    /**
     * 得到当前日期和时间字符串 格式（yyyy-MM-dd HH:mm:ss）
     */
    public static String getDateTimes() {
        return formatDate(new Date(), "yyyy-MM-dd HH:mm");
    }

    /**
     * 得到当前年份字符串 格式（yyyy）
     */
    public static String getYear() {
        return formatDate(new Date(), "yyyy");
    }

    /**
     * 得到当前月份字符串 格式（MM）
     */
    public static String getMonth() {
        return formatDate(new Date(), "MM");
    }

    /**
     * 得到当天字符串 格式（dd）
     */
    public static String getDay() {
        return formatDate(new Date(), "dd");
    }

    /**
     *
     */
    public static int getWeekDay(Date date) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        return cal.get(Calendar.DAY_OF_WEEK);
    }

    /**
     * 得到当前星期字符串 格式（E）星期几
     */
    public static String getWeek() {
        return formatDate(new Date(), "E");
    }

    /**
     * 得到当前星期字符串 格式（E）星期几
     */
    public static String getWeek(Date date) {
        return formatDate(date, "E");
    }


    /**
     * 得到当前星期字符串 星期几
     */
    public static String getWeekDay(Date date,String prefix) {
        String week = "";
        int cweek = getWeekDay(date);
        switch (cweek) {
            case 1:
                week = "日";
                break;
            case 2:
                week = "一";
                break;
            case 3:
                week = "二";
                break;
            case 4:
                week = "三";
                break;
            case 5:
                week = "四";
                break;
            case 6:
                week = "五";
                break;
            case 7:
                week = "六";
                break;
        }
        return StringUtils.isBlank(prefix) ? week : prefix + week;
    }

    /**
     * 日期型字符串转化为日期 格式 { "yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm",
     * "yyyy/MM/dd", "yyyy/MM/dd HH:mm:ss", "yyyy/MM/dd HH:mm", "yyyy.MM.dd",
     * "yyyy.MM.dd HH:mm:ss", "yyyy.MM.dd HH:mm" }
     */
    public static Date parseDate(String str) {
        if (str == null) {
            return null;
        }
        try {
            return org.apache.commons.lang3.time.DateUtils.parseDate(str, parsePatterns);
        } catch (java.text.ParseException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 获取过去的天数
     *
     * @param date
     * @return
     */
    public static long pastDays(Date date) {
        long t = new Date().getTime() - date.getTime();
        return t / (24 * 60 * 60 * 1000);
    }

    /**
     * 获取过去的小时
     *
     * @param date
     * @return
     */
    public static long pastHour(Date date) {
        long t = new Date().getTime() - date.getTime();
        return t / (60 * 60 * 1000);
    }

    /**
     * 获取过去的分钟
     *
     * @param date
     * @return
     */
    public static long pastMinutes(Date date) {
        long t = new Date().getTime() - date.getTime();
        return t / (60 * 1000);
    }

    /**
     * 转换为时间（天,时:分:秒.毫秒）
     *
     * @param timeMillis
     * @return
     */
    public static String formatDateTime(long timeMillis) {
        long day = timeMillis / (24 * 60 * 60 * 1000);
        long hour = (timeMillis / (60 * 60 * 1000) - day * 24);
        long min = ((timeMillis / (60 * 1000)) - day * 24 * 60 - hour * 60);
        long s = (timeMillis / 1000 - day * 24 * 60 * 60 - hour * 60 * 60 - min * 60);
        long sss = (timeMillis - day * 24 * 60 * 60 * 1000 - hour * 60 * 60
                * 1000 - min * 60 * 1000 - s * 1000);
        return (day > 0 ? day + "," : "") + hour + ":" + min + ":" + s + "."
                + sss;
    }

    /**
     * 获取两个日期之间的天数
     *
     * @param before
     * @param after
     * @return
     */
    public static double getDistanceOfTwoDate(Date before, Date after) {
        if (before == null){
            return -1.0;
        }
        if (after == null){
            return 1;
        }
        long beforeTime = before.getTime();
        long afterTime = after.getTime();
        return (afterTime - beforeTime) / (1000 * 60 * 60 * 24);
    }

    /**
     * 比较两个日期相差的月数
     */
    public static int getMonthMargin(String date1, String date2) {
        int margin;
        try {
            margin = (Integer.parseInt(date2.substring(0, 4)) - Integer.parseInt(date1.substring(0, 4))) * 12;
            margin += (Integer.parseInt(date2.substring(4, 7).replaceAll("-0", "-")) - Integer.parseInt(date1.substring(4, 7).replaceAll("-0", "-")));
            return margin;
        } catch (Exception e) {
            return 0;
        }
    }

    /**
     * 根据身份证的号码算出当前身份证持有者的性别和年龄 18位身份证
     *
     * @return
     * @throws Exception
     */
    public static Map<String, Object> getCarInfo(String CardCode)
    {
        Map<String, Object> map = new HashMap<String, Object>();
        String year = CardCode.substring(6).substring(0, 4);// 得到年份
        String yue = CardCode.substring(10).substring(0, 2);// 得到月份
        String day=CardCode.substring(12).substring(0,2);//得到日
        String sex;
        if (Integer.parseInt(CardCode.substring(16).substring(0, 1)) % 2 == 0) {// 判断性别
            sex = "女";
        } else {
            sex = "男";
        }
        Date date = new Date();// 得到当前的系统时间
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        String fyear = format.format(date).substring(0, 4);// 当前年份
        String fyue = format.format(date).substring(5, 7);// 月份
        // String fday=format.format(date).substring(8,10);
        int age = 0;
        if (Integer.parseInt(yue) <= Integer.parseInt(fyue)) { // 当前月份大于用户出身的月份表示已过生
            age = Integer.parseInt(fyear) - Integer.parseInt(year);
        } else {// 当前用户还没过生
            age = Integer.parseInt(fyear) - Integer.parseInt(year) -1;
        }
        map.put("sex", sex);
        map.put("age", age);
        map.put("birthday",year+"-"+yue+"-"+day);
        return map;
    }

    /**
     * 通过身份证号码判断年龄以及性别
     * 15位身份证的验证
     * @param
     * @throws Exception
     */
    public static Map<String, Object> getCarInfo15w(String card)
    {
        Map<String, Object> map = new HashMap<String, Object>();
        String uyear = "19" + card.substring(6, 8);// 年份
        String uyue = card.substring(8, 10);// 月份
        String uday=card.substring(10, 12);//日
        String usex = card.substring(14, 15);// 用户的性别
        String sex;
        if (Integer.parseInt(usex) % 2 == 0) {
            sex = "女";
        } else {
            sex = "男";
        }
        Date date = new Date();// 得到当前的系统时间
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        String fyear = format.format(date).substring(0, 4);// 当前年份
        String fyue = format.format(date).substring(5, 7);// 月份
        // String fday=format.format(date).substring(8,10);
        int age = 0;
        if (Integer.parseInt(uyue) <= Integer.parseInt(fyue)) { // 当前月份大于用户出身的月份表示已过生
            age = Integer.parseInt(fyear) - Integer.parseInt(uyear);
        } else {// 当前用户还没过生
            age = Integer.parseInt(fyear) - Integer.parseInt(uyear)-1;
        }
        map.put("sex", sex);
        map.put("age", age);
        map.put("birthday",uyear+"-"+uyue+"-"+"uday");
        return map;
    }

    /**
     * 两个日期比较，获取相差年月日
     * @param startDateStr
     * @param endDateStr
     * @return
     */
    public static Map<String,Integer> remainDateToString(String startDateStr, String endDateStr){
        Date startDate = null;
        Date endDate= null;
        try {
            startDate = new SimpleDateFormat("yyyy-MM-dd").parse(startDateStr);
            endDate = new SimpleDateFormat("yyyy-MM-dd").parse(endDateStr);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        calS.setTime(startDate);
        int startY = calS.get(Calendar.YEAR);
        int startM = calS.get(Calendar.MONTH);
        int startD = calS.get(Calendar.DATE);
        int startDayOfMonth = calS.getActualMaximum(Calendar.DAY_OF_MONTH);

        calS.setTime(endDate);
        int endY = calS.get(Calendar.YEAR);
        int endM = calS.get(Calendar.MONTH);
        int endD = calS.get(Calendar.DATE)+1;
        int endDayOfMonth = calS.getActualMaximum(Calendar.DAY_OF_MONTH);

        if (endDate.compareTo(startDate)<0) {
            return null;
        }
        Map<String,Integer> rMap = new HashMap<>();
        int lday = endD-startD;
        if (lday<0) {
            endM = endM -1;
            lday = startDayOfMonth+ lday;
        }
        if (lday == endDayOfMonth) {
            endM = endM+1;
            lday =0;
        }
        int mos = (endY - startY)*12 + (endM- startM);
        int lyear = mos/12;
        int lmonth = mos%12;
        rMap.put("year",lyear);
        rMap.put("month",lmonth);
        rMap.put("day",lday);
        return rMap;
    }

    /**
     * Date日期+天数
     * @param date 传入日期
     * @param index 天数
     * @return
     */
    public static Date getAddDay(Date date,int index) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.DAY_OF_MONTH, +index);//时间加index天
        date = calendar.getTime();
        return date;
    }

    /**
     * 比较两个时间大小
     *
     * @param DATE1
     * @param DATE2
     * @return
     */
    public static int compare_time(String DATE1, String DATE2,String pattern) {
        DateFormat df = new SimpleDateFormat(pattern);
        Date time1 = null;
        Date time2 = null;
        try {
            time1 = df.parse(DATE1);
            time2 = df.parse(DATE2);
        } catch (Exception exception) {
            exception.printStackTrace();
        }
        return time1.compareTo(time2);
    }




    /**
     * 根据出生年月算出年龄
     *
     * @param birthDay
     * @return
     */
    public static int getAge(Date birthDay) {
        Calendar cal = Calendar.getInstance();
        int yearNow = cal.get(Calendar.YEAR);
        int monthNow = cal.get(Calendar.MONTH);
        int dayOfMonthNow = cal.get(Calendar.DAY_OF_MONTH);
        cal.setTime(birthDay);

        int yearBirth = cal.get(Calendar.YEAR);
        int monthBirth = cal.get(Calendar.MONTH);
        int dayOfMonthBirth = cal.get(Calendar.DAY_OF_MONTH);

        int age = yearNow - yearBirth;

        if (monthNow <= monthBirth) {
            if (monthNow == monthBirth) {
                if (dayOfMonthNow < dayOfMonthBirth) age--;
            }else{
                age--;
            }
        }
        return age;
    }

    public static Date parseDate(String str,String[] parsePatterns) {
        if (str == null) {
            return null;
        }
        try {
            return org.apache.commons.lang3.time.DateUtils.parseDate(str, parsePatterns);
        } catch (java.text.ParseException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 功能描述: 判断时间是否在时间段内
     * @auther: cnsu-cmh
     * @date: 2019-12-03
     */
    public static boolean belongCalendar(Date nowTime, Date beginTime, Date endTime) {
        Calendar date = Calendar.getInstance();
        date.setTime(nowTime);

        Calendar begin = Calendar.getInstance();
        begin.setTime(beginTime);

        Calendar end = Calendar.getInstance();
        end.setTime(endTime);

        if (date.after(begin) && date.before(end)) {
            return true;
        } else {
            return false;
        }
    }

    public static List<String> getIntervalTimeList(String start, String end, int interval) {
        String[] parsePatterns = new String[]{"HHmmss"};
        Date startDate = parseDate(start,parsePatterns);
        Date endDate = parseDate(end,parsePatterns);
        List<String> list = new ArrayList<>();
        while(startDate.getTime() <= endDate.getTime()){
            list.add(formatDate(startDate,parsePatterns));
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(startDate);
            calendar.add(Calendar.SECOND,interval/1000);
            if(calendar.getTime().getTime() > endDate.getTime()){
                if(!startDate.equals(endDate)){
                    list.add(formatDate(endDate,parsePatterns));
                }
                startDate = calendar.getTime();
            }else{
                startDate = calendar.getTime();
            }
        }
        return list;
    }

    public static int getTimeMilliSecond(String start,String end) {
        String[] parsePatterns = new String[]{"yyyyMMddHHmmss"};
        Date startDate = parseDate(start,parsePatterns);
        Date endDate = parseDate(end,parsePatterns);
        long a = startDate.getTime();
        long b = endDate.getTime();
        int c = (int)((b - a));
        return c;
    }

    /**
     * 比较两个时间大小（与当前时间）
     *
     * @param time
     * @return
     */
    public static int compare_time(String time) {
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date time1 = new Date();
        Date time2 = null;
        try {
            time2 = df.parse(DateUtils.formatDate(new Date())+" "+time);
        } catch (Exception exception) {
            exception.printStackTrace();
        }
        return time1.compareTo(time2);
    }

    /**
     * 日期相隔天数
     *
     * @param startDateInclusive
     * @param endDateExclusive
     * @return
     */
    public static int periodDays(LocalDate startDateInclusive, LocalDate endDateExclusive) {
        return Period.between(startDateInclusive, endDateExclusive).getDays();
    }

    /**
     * 日期相隔天数(与当前时间)
     *
     * @param dateStr
     * @return
     */
    public static int periodDays(String dateStr,String pattern) {
        LocalDate startDateInclusive = getCurrentLocalDate();
        LocalDate endDateExclusive = parseLocalDate(dateStr,pattern);
        return Period.between(startDateInclusive, endDateExclusive).getDays();
    }

    /**
     * 日期相隔天数(与当前时间 yyyy-MM-dd)
     *
     * @param dateStr
     * @return
     */
    public static int periodDays(String dateStr) {
        LocalDate startDateInclusive = getCurrentLocalDate();
        LocalDate endDateExclusive = parseLocalDate(dateStr,"yyyy-MM-dd");
        return Period.between(startDateInclusive, endDateExclusive).getDays();
    }

    /**
     * 返回当前的日期
     *
     * @return
     */
    public static LocalDate getCurrentLocalDate() {
        return LocalDate.now();
    }

    public static LocalDate parseLocalDate(String dateStr, String pattern) {
        return LocalDate.parse(dateStr, DateTimeFormatter.ofPattern(pattern));
    }

    public static String dateToStr(Date date, String formatType) {
        if (date == null) {
            return null;
        }
        SimpleDateFormat format = new SimpleDateFormat(formatType);
        return format.format(date);
    }

    public static Date strToDate(String strDate){
        if (StringUtils.isBlank(strDate)) {
            return null;
        }
        SimpleDateFormat format = new SimpleDateFormat(DateUtils.FORMAT_DEFAULT);
        try {
            return format.parse(strDate);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 两个时间相差的分钟数
     * @param startDate
     * @param endDate
     * @return 小于0的返回0其他返回正数
     */
    public static long dateScopeChineseMin(Date startDate, Date endDate){
        //相差毫秒数
        long gap = endDate.getTime() - startDate.getTime();
        if(gap < 0){
            return 0;
        }

        long sizeDay = 1000 * 24 * 60 * 60;
        long sizeHour = 1000 * 60 * 60;
        long sizeMinute = 1000 * 60;
        long sizeSeconds = 1000;

        return gap % sizeDay % sizeHour / sizeMinute;
    }

    /**
     * Long类型时间->转换成日期->转成要求格式的String类型
     */
    public static String fromLongToDate(String format, Long time) {
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        Date date = new Date(time);
        return sdf.format(date);
    }
}
